package spark.graphics;

import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;

import java.util.HashMap;

public class SpriteMapParser extends DefaultHandler {
	static final String ELE_THEME = "theme";
	static final String ATT_NAME = "name";
	private static final String ATT_PATH = "path";
	static final String ELE_SPRITE = "sprite";
	private static final String ATT_OPAQUE = "opaque";
	private static final String TRUE = "true";
	private static final String ELE_POS = "position";
	private static final String ATT_X = "x";
	private static final String ATT_Y = "y";
	private static final String ELE_DIM = "dimensions";
	private static final String ATT_WIDTH = "width";
	private static final String ATT_HEIGHT = "height";
	private String theme;
	private String themePath;
	private HashMap<String, SpriteMap.SpriteData> spriteDataMap;
	private String currentName;
	private SpriteMap.SpriteData current;

	public SpriteMapParser(String theme, HashMap<String, SpriteMap.SpriteData> spriteDataMap) {
		this.theme = theme;
		this.spriteDataMap = spriteDataMap;
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if(localName.equals(ELE_THEME)) {
			if(attributes.getValue(ATT_NAME).equals(theme)) {
				themePath = attributes.getValue(ATT_PATH);
			}
		}
		else if(localName.equals(ELE_SPRITE)) {
			currentName = attributes.getValue(ATT_NAME);
			if(currentName.equals("")) {
				currentName = " ";
			}
			current = new SpriteMap.SpriteData();
			spriteDataMap.put(currentName, current);
			current.opaque = TRUE.equals(attributes.getValue(ATT_OPAQUE));
		}
		else if(localName.equals(ELE_POS)) {
			try {
				current.uv.x = Integer.parseInt(attributes.getValue(ATT_X));
				current.uv.y = Integer.parseInt(attributes.getValue(ATT_Y));
			}
			catch(NumberFormatException e) {
				throw new SAXException("Invalid value on " + ELE_POS + " at " + ELE_SPRITE + " " + currentName);
			}
		}
		else if(localName.equals(ELE_DIM)) {
			try {
				current.dimensions.x = Integer.parseInt(attributes.getValue(ATT_WIDTH));
				current.dimensions.y = Integer.parseInt(attributes.getValue(ATT_HEIGHT));
			}
			catch(NumberFormatException e) {
				throw new SAXException("Invalid value on " + ELE_DIM + " at " + ELE_SPRITE + " " + currentName);
			}
		}
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
		if(themePath == null) {
			throw new SAXException("Theme " + theme + " not contained");
		}
	}

	public String getThemeFileName() {
		return themePath;
	}
}
